package core.proto.search;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;

import core.proto.AllComponents;
import core.proto.PaintDoc;
import core.proto.TextHighlighter;
import core.proto.Util;

public class DocumentSearchDocumentListener implements DocumentListener {

	PaintDoc doc;

	public  DocumentSearchDocumentListener (PaintDoc doc){
		this.doc = doc;	
	}

	void searchDoc(String term) {
		term = term.trim().toLowerCase();
		doc.clearSearchHighlights();

		if (term.length() == 0)
			return;
		
		try {
			Document docum = doc.getDocument();
			String text = docum.getText(0, docum.getLength());
			text = text.toLowerCase();
			int pos = 0;
			while ((pos = text.indexOf(term, pos)) >= 0) {
				doc.addSearchHighlight(pos, pos + term.length());
				pos += term.length();
			}
		} catch (BadLocationException e) {
		}
//		AllComponents.removeHighlights(doc);
//		term = term.trim().toLowerCase();
//		
//		if (term.length() == 0)
//			return;
//		
//		try {
//			Highlighter hilite;
//			Document docum;
//			hilite = doc.getHighlighter();
//			docum = doc.getDocument();
//
//			String text = docum.getText(0, docum.getLength());
//			text = text.toLowerCase();
//			int pos = 0;
//			while ((pos = text.indexOf(term, pos)) >= 0) {
//				hilite.addHighlight(pos, pos + term.length(), myHighlightPainter);
//				pos += term.length();
//			}
//			doc.repaint();
//		} catch (BadLocationException e) {
//		}
	}

	@Override
	public void changedUpdate(DocumentEvent de) {
		// No op
	}

	@Override
	public void insertUpdate(DocumentEvent de) {
		try {
			searchDoc(de.getDocument().getText(0, de.getDocument().getLength()));
		} catch (BadLocationException e) {
			throw new Error(e);
		}
	}

	@Override
	public void removeUpdate(DocumentEvent de) {
		try {
			searchDoc(de.getDocument().getText(0, de.getDocument().getLength()));
		} catch (BadLocationException e) {
			throw new Error(e);
		}
	}
}
